/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;

import common.Helper;
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 *
 */
public class ReceiveThread extends UnicastRemoteObject implements IReceiveThread, Runnable {
    private Buffer buffer;

    public ReceiveThread(Buffer buffer) throws RemoteException{
        this.buffer = buffer;
    }

    public void put(BufferMessage bufferMessage) throws RemoteException {
        buffer.put(bufferMessage);
        System.out.println(
                "[debug] " +
                "Process: " + Helper.getProcessId() + "; "+
                "Thread: " + Thread.currentThread().getName() + ";\n" +
                "[debug] " +
                "Action: receivingThread.receive()" + " -> " + bufferMessage + "\n");
    }

    public void run()
    {
        try
        {
            LocateRegistry.createRegistry(1099);
            Logger.getLogger(ReceiveThread.class.getName()).log(
                    Level.INFO, "RMI registry created.");
        } catch (RemoteException ex) // the RMI registry already exists
        {
            Logger.getLogger(ReceiveThread.class.getName()).log(
                    Level.INFO, "The RMI registry already exists.");
        }

        try
        {
            // will look like "rmi://localhost/processX/receiveBuffer"
            String receiveBufferRmiAddress =
                    Helper.getCurrentProcessRmiAddressPreffix();
            receiveBufferRmiAddress += "receiveBuffer";
            Naming.rebind(receiveBufferRmiAddress, this);
            Logger.getLogger(ReceiveThread.class.getName()).log(
                    Level.INFO, "binding: " + receiveBufferRmiAddress);
            // Only register itself once it's ready to receive
            Helper.registerToProcessManager();

        } catch (IOException ex)
        {
            Logger.getLogger(ReceiveThread.class.getName()).log(
                    Level.SEVERE, null, ex);
        }   
    }

}
